<template>
    <div class="login-bg">
        <div class="login-container">
            <div class="login-card">
                <div class="login-title">智慧会议管理平台</div>
                <div class="login-subtitle">Smart Conference Management Platform</div>
                <el-tabs v-model="activeTab" class="login-tabs">
                    <el-tab-pane label="账户密码登录" name="account"></el-tab-pane>
                    <el-tab-pane label="手机号登录" name="phone"></el-tab-pane>
                </el-tabs>
                <el-form :model="form" :rules="rules" ref="formRef" class="login-form">
                    <template v-if="activeTab === 'account'">
                        <el-form-item prop="account">
                            <el-input v-model="form.account" placeholder="账号/手机号" :prefix-icon="User" />
                        </el-form-item>
                        <el-form-item prop="password">
                            <el-input v-model="form.password" placeholder="密码" :prefix-icon="Lock" show-password />
                        </el-form-item>

                        <el-form-item prop="Imagecaptcha">
                            <el-row :gutter="10" style="width: 100%">
                                <el-col :span="16">
                                    <el-input v-model="form.Imagecaptcha" placeholder="验证码" :prefix-icon="Lock"
                                        maxlength="6" @input="onCaptchaInput" />
                                </el-col>
                                <el-col :span="8">
                                    <div class="captcha-container" @click="refreshCaptcha">
                                        <img :src="captchaImage" alt="验证码" style="width: 100%; height: 100%;">
                                        <div v-if="loading" class="captcha-loading">加载中...</div>
                                    </div>
                                </el-col>
                            </el-row>
                        </el-form-item>


                    </template>
                    <template v-else>
                        <el-form-item prop="phone">
                            <el-input v-model="form.phone" placeholder="手机号" :prefix-icon="Iphone" />
                        </el-form-item>

                        <el-form-item prop="code">
                            <el-row :gutter="10" style="width: 100%">
                                <el-col :span="16">
                                    <el-input v-model="form.code" placeholder="验证码" :prefix-icon="Lock" />
                                </el-col>
                                <el-col :span="8">
                                    <el-button @click="getCode" :disabled="countdown > 0" style="width: 100%">
                                        {{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
                                    </el-button>
                                </el-col>
                            </el-row>
                        </el-form-item>
                    </template>
                    <el-form-item>
                        <el-checkbox v-model="form.autoLogin">自动登录</el-checkbox>
                        <a class="login-link" @click.prevent>忘记密码</a>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" style="width: 100%" @click="onLogin">登 录</el-button>
                    </el-form-item>
                </el-form>
                <div class="login-other">
                    <span>其他登录方式</span>
                    <span class="login-icon" title="微信登录">
                        <svg width="28" height="28" viewBox="0 0 66 66" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <g>
                                <ellipse cx="34.5" cy="32.5" rx="24.5" ry="20.5" fill="#7ED321" />
                                <ellipse cx="48.5" cy="48.5" rx="13.5" ry="11.5" fill="#F7F7F7" />
                                <circle cx="27" cy="32" r="2.5" fill="#222" />
                                <circle cx="42" cy="32" r="2.5" fill="#222" />
                                <circle cx="44.5" cy="48.5" r="2" fill="#888" />
                                <circle cx="53.5" cy="48.5" r="2" fill="#888" />
                            </g>
                        </svg>
                    </span>
                    <span class="login-icon" title="QQ登录">
                        <svg viewBox="0 0 48 48" width="24" height="24">
                            <circle cx="24" cy="24" r="24" fill="#12B7F5" />
                            <path
                                d="M24 12c-4.4 0-8 3.6-8 8 0 2.2 1.1 4.2 2.8 5.5C17.3 27.2 16 29.5 16 32h16c0-2.5-1.3-4.8-2.8-6.5C30.9 24.2 32 22.2 32 20c0-4.4-3.6-8-8-8z"
                                fill="#fff" />
                        </svg>
                    </span>
                    <span class="login-icon" title="微博登录">
                        <svg viewBox="0 0 48 48" width="24" height="24">
                            <circle cx="24" cy="24" r="24" fill="#F56C6C" />
                            <path
                                d="M24 16c-4.4 0-8 2.7-8 6s3.6 6 8 6 8-2.7 8-6-3.6-6-8-6zm-2 7.5c-.8 0-1.5-.7-1.5-1.5S21.2 20.5 22 20.5s1.5.7 1.5 1.5S22.8 23.5 22 23.5zm4 0c-.8 0-1.5-.7-1.5-1.5S25.2 20.5 26 20.5s1.5.7 1.5 1.5S26.8 23.5 26 23.5z"
                                fill="#fff" />
                        </svg>
                    </span>
                </div>
                <div class="login-footer">
                    <a class="login-link" @click="goToRegister">注册账户</a>
                </div>
                <div class="login-copyright">
                    copyright©2024 XXXXXXXXXXXXXXXXXXXXXXXX
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Lock, Iphone } from '@element-plus/icons-vue'
import { login, getCaptcha, verifyCaptcha } from '@/api/user'
import type { LoginData, VerificationData } from '@/api/user'
import { setToken } from '@/utils/auth'
import { useRouter } from 'vue-router'
import { useStore } from '@/stores/userInfo'
import { useMenuStore } from '@/stores/menuStore'

const router = useRouter()
const userStore = useStore()
const activeTab = ref('account')
const formRef = ref()
const form = ref({
    account: '',
    password: '',
    phone: '',
    code: '',
    Imagecaptcha: '',//图片验证码
    autoLogin: false
})

// 验证码相关
const captchaImage = ref('')
const captchaId = ref('') // 保存当前验证码的ID，用于验证
let currentBlobUrl = '' // 保存当前blob URL，用于清理
const loading = ref(false) // 添加loading状态变量

// 从服务器获取验证码
const refreshCaptcha = async () => {
    try {
        loading.value = true;

        // 如果存在之前的blob URL，需要释放它以防止内存泄漏
        if (captchaImage.value && captchaImage.value.startsWith('blob:')) {
            URL.revokeObjectURL(captchaImage.value);
        }

        // 从userStore获取userid，如果没有则生成随机ID
        const userId = userStore.userinfo.userid || Math.floor(Math.random() * 10000).toString();

        console.log('正在获取验证码，userId:', userId);

        // 获取验证码，使用类型断言处理响应
        const response = await getCaptcha(userId) as any;
        console.log("验证码响应:", response); // 这是一个二进制Blob数据

        // 创建一个URL对象来显示图片
        const blobUrl = URL.createObjectURL(response);
        captchaImage.value = blobUrl;

        // 保存验证码ID
        captchaId.value = userId;

        loading.value = false;
    } catch (error) {
        console.error('获取验证码失败', error);
        ElMessage.error('获取验证码失败，请重试');
        loading.value = false;
    }
}

const rules = {
    account: [
        { required: true, message: '请输入账号/手机号', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
    ],
    code: [
        { required: true, message: '请输入验证码', trigger: 'blur' }
    ],
    Imagecaptcha: [
        { required: true, message: '请输入验证码', trigger: 'blur' }
    ]
}

const countdown = ref(0)
let timer: any = null

// 自动登录本地存储key
const ACCOUNT_KEY = 'login_account'
const PASSWORD_KEY = 'login_password'
const AUTOLOGIN_KEY = 'login_autoLogin'

function saveLoginInfo() {
    if (form.value.autoLogin) {
        localStorage.setItem(ACCOUNT_KEY, form.value.account)
        localStorage.setItem(PASSWORD_KEY, form.value.password)
        localStorage.setItem(AUTOLOGIN_KEY, 'true')
    } else {
        localStorage.removeItem(ACCOUNT_KEY)
        localStorage.removeItem(PASSWORD_KEY)
        localStorage.removeItem(AUTOLOGIN_KEY)
    }
}

function loadLoginInfo() {
    const auto = localStorage.getItem(AUTOLOGIN_KEY) === 'true'
    if (auto) {
        form.value.account = localStorage.getItem(ACCOUNT_KEY) || ''
        form.value.password = localStorage.getItem(PASSWORD_KEY) || ''
        form.value.autoLogin = true
    }
}

function getCode() {
    if (!/^1[3-9]\d{9}$/.test(form.value.phone)) {
        ElMessage.error('请输入正确的手机号')
        return
    }
    ElMessage.success('验证码已发送')
    countdown.value = 60
    timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
            clearInterval(timer)
            timer = null
        }
    }, 1000)
}

// 跳转到注册页面
function goToRegister() {
    router.push('/register');
}

// 处理验证码输入，确保正确格式
const onCaptchaInput = (val: string) => {
    // 可以在这里添加额外的验证码处理逻辑
    // 例如限制特定字符、转换大小写等
    console.log('验证码输入:', val);

    // 最好保持用户输入的原始值，不要自动转换大小写
    // 如果后端对验证码区分大小写
}

// 手动定义API响应类型接口
interface ApiResponse<T> {
    Data: T;
    IsSuc: boolean;
    Code: number;
    Msg: string;
}

async function onLogin() {
    await formRef.value.validate(async (valid: boolean) => {
        if (!valid) return
        try {
            // 账户密码登录时需要先验证验证码
            if (activeTab.value === 'account') {
                // 准备验证码验证参数
                const verifyData: VerificationData = {
                    CaptchaId: captchaId.value,
                    CaptchaImage: form.value.Imagecaptcha  // 这里是用户输入的验证码值
                }

                console.log('验证码验证参数:', verifyData);

                try {
                    // 调用验证码验证接口
                    const verifyResponse = await verifyCaptcha(verifyData) as any;
                    console.log('验证码验证结果:', verifyResponse);

                    // 如果验证码验证失败，提示错误并刷新验证码
                    if (!verifyResponse.IsSuc) {
                        ElMessage.error(verifyResponse.Msg || '验证码错误');
                        refreshCaptcha();
                        form.value.Imagecaptcha = '';
                        return;
                    }

                    // 验证通过
                    console.log('验证码验证通过');
                } catch (verifyError: any) {
                    console.error('验证码验证失败:', verifyError);
                    ElMessage.error('验证码验证失败，请重试');
                    refreshCaptcha();
                    form.value.Imagecaptcha = '';
                    return;
                }

                // 验证码验证通过，继续登录流程
                console.log('验证码验证通过，继续登录流程');
            }

            // 准备登录参数
            let params: Record<string, any> = {}

            if (activeTab.value === 'account') {
                params = {
                    UserName: form.value.account.trim(),
                    Password: form.value.password
                    // 不再需要传递验证码，因为已经在前一步验证过了
                }
            } else {
                params = {
                    phone: form.value.phone.trim(),
                    code: form.value.code.trim()
                }
            }

            console.log('即将发送登录请求，参数:', JSON.stringify(params));

            const response = await login(params) as any;
            console.log('登录响应:', response);

            // 检查响应状态
            if (!response.IsSuc) {
                ElMessage.error(response.Msg || '登录失败');
                // 登录失败但不一定是验证码问题，此处不需要刷新验证码
                return;
            }

            // 获取用户数据
            const userData = response.Data as LoginData;

            // 保存Token
            setToken(userData.Token);

            // 保存用户信息
            localStorage.setItem('user_info', JSON.stringify(userData));

            // 如果选择了自动登录，保存账号密码
            if (activeTab.value === 'account') {
                saveLoginInfo();
            }

            // 登录成功后的处理
            handleLoginSuccess(userData);

        } catch (error: any) {
            console.error('登录失败:', error);
            ElMessage.error(error.message || '登录失败');

            // 登录失败，刷新验证码
            if (activeTab.value === 'account') {
                refreshCaptcha();
                form.value.Imagecaptcha = '';
            }
        }
    })
}

// 登录成功后的处理
const handleLoginSuccess = (response: any) => {
    // 创建一个标准格式的用户数据对象
    const standardUserData = {
        Token: response.Token,
        UserId: response.UserId,
        UserName: response.UserName,
        RealName: response.RealName || response.UserName,
        RoleId: response.RoleId || 0,  // 确保RoleId存在
        role: response.RoleId || 0     // 同时保存role字段，保持兼容性
    }

    console.log('标准化用户数据:', standardUserData)

    // 重置用户信息，确保清除旧数据
    userStore.resetUserInfo()

    // 存储用户信息到pinia store
    userStore.userinfo.usertoken = standardUserData.Token
    userStore.userinfo.userid = standardUserData.UserId
    userStore.userinfo.username = standardUserData.UserName
    userStore.userinfo.realname = standardUserData.RealName

    // 设置用户角色ID
    userStore.userinfo.role = standardUserData.RoleId

    // 初始化默认权限
    userStore.initDefaultPermissions()

    // 同时在工具函数中设置token，确保一致性
    setToken(standardUserData.Token)

    // 保存标准化用户信息到localStorage
    localStorage.setItem('user_info', JSON.stringify(standardUserData))

    // 加载菜单数据
    const menuStore = useMenuStore()

    // 清空菜单状态
    menuStore.menuList = []

    // 显示登录成功消息
    ElMessage.success('登录成功')

    // 尝试从后端加载菜单
    menuStore.fetchMenus().then(() => {
        // 确保菜单加载完成后再跳转
        
        // 检查菜单是否为空
        if (menuStore.menuList.length === 0) {
            console.warn('菜单列表为空，初始化默认菜单')
            menuStore.initDefaultMenus()
        }

        // 跳转到首页的dashboard子路由
        router.push('/index/dashboard')
    }).catch(error => {
        console.error('菜单加载失败:', error)

        // 菜单加载失败时，使用默认菜单
        menuStore.initDefaultMenus()

        // 即使菜单加载失败，也跳转到首页
        router.push('/index/dashboard')
    })
}

// 当切换到账号登录模式时，自动生成验证码
watch(activeTab, (newVal) => {
    formRef.value && formRef.value.resetFields()
    if (newVal === 'account') {
        loadLoginInfo()
        refreshCaptcha() // 切换到账号登录时自动刷新验证码
    }
})

// 页面加载时自动反填账号密码和生成验证码
onMounted(() => {
    if (activeTab.value === 'account') {
        loadLoginInfo()
        refreshCaptcha() // 页面加载时生成验证码
    }
})

// 组件卸载时释放资源
onUnmounted(() => {
    // 如果存在blob验证码图片，释放资源
    if (captchaImage.value && captchaImage.value.startsWith('blob:')) {
        URL.revokeObjectURL(captchaImage.value);
    }
    if (timer) {
        clearInterval(timer);
    }
})
</script>

<style scoped>
.login-bg {
    min-height: 100vh;
    background: url('https://images.unsplash.com/photo-1519389950473-47ba0277781c?auto=format&fit=crop&w=1500&q=80') center center/cover no-repeat;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow-x: hidden;
    /* 防止水平滚动 */
    position: fixed;
    /* 固定背景 */
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}

.login-container {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(0, 0, 0, 0.2);
    overflow: hidden;
    /* 防止内容溢出 */
}

.login-card {
    width: 400px;
    background: rgba(255, 255, 255, 0.98);
    border-radius: 10px;
    box-shadow: 0 4px 32px rgba(0, 0, 0, 0.12);
    padding: 40px 36px 24px 36px;
    display: flex;
    flex-direction: column;
    align-items: stretch;
    position: relative;
}

.login-title {
    font-size: 26px;
    font-weight: bold;
    color: #222;
    text-align: center;
    margin-bottom: 6px;
}

.login-subtitle {
    font-size: 14px;
    color: #888;
    text-align: center;
    margin-bottom: 24px;
}

.login-tabs {
    margin-bottom: 18px;
}

.login-form {
    margin-bottom: 8px;
}

.login-link {
    color: #409EFF;
    margin-left: 12px;
    font-size: 13px;
    cursor: pointer;
}

.login-other {
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 18px 0 8px 0;
    color: #888;
    font-size: 13px;
}

.login-icon {
    margin: 0 8px;
    cursor: pointer;
    display: flex;
    align-items: center;
    transition: transform 0.2s;
}

.login-icon:hover {
    transform: scale(1.15);
    filter: brightness(1.1);
}

.login-footer {
    text-align: right;
    margin-bottom: 8px;
}

.login-copyright {
    text-align: center;
    color: #bbb;
    font-size: 12px;
    margin-top: 10px;
}

.captcha-container {
    cursor: pointer;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    position: relative;
    overflow: hidden;
}

.captcha-container:hover::after {
    content: '点击刷新';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
}

.captcha-container img {
    max-height: 100%;
    max-width: 100%;
}

.captcha-loading {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 4px;
    font-size: 12px;
    color: #409EFF;
}

@media (max-width: 500px) {
    .login-card {
        width: 90%;
        max-width: 400px;
        padding: 24px 16px 12px 16px;
    }
}
</style>